package com.example.controller;

import com.example.pojo.User;
import com.example.service.UserService;
import com.example.util.CodeUtil;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class LoginCtrl {

    @Resource
    private UserService userService;

    @Autowired
    private DefaultKaptcha defaultKaptcha;

    @RequestMapping("login")
    public String login(){
        return "login";
    }
    @RequestMapping("reg")
    public String reg(){
        return "reg";
    }
    @RequestMapping("list")
    public String list(){
        return "list";
    }


    @RequestMapping("loginDo")
    @ResponseBody
    public Map<String,Object> loginDo(@Validated User user, Errors errors, HttpSession session, String code){
        System.out.println(code);
        Map<String,Object> resultMap = new HashMap<>();
        if (!CodeUtil.checkVerifyCode(session, code)) {
            resultMap.put("code", false);
        } else {
            resultMap.put("code", true);
            try {
                List<FieldError> fieldErrors = errors.getFieldErrors();
                if(fieldErrors==null||fieldErrors.size()==0) {
                    User loginUser = userService.login(user);
                    if (loginUser != null) {
                        session.setAttribute("loginUser", loginUser);
                        resultMap.put("result", true);
                    } else {
                        resultMap.put("result", false);
                    }
                }else{
                    resultMap.put("result", false);
                    for (FieldError f:fieldErrors) {
                        resultMap.put(f.getField(),f.getDefaultMessage());
                    }
                }
            }catch (Exception e){
                resultMap.put("result",false);
            }
        }

        return resultMap;
    }
    @RequestMapping("listDo")
    public String listDo(Model model){
        List<User> userList = userService.findAll();
        model.addAttribute("userList",userList);
        return "list";
    }
    @RequestMapping("resetPsw")
    public String resetPwd(Integer userId){
        User user = userService.selectOne(userId);
        System.out.println(user);
        userService.resetPsw(user);
        return "redirect:listDo";
    }

    @RequestMapping("code")
    public void defaultKaptcha(HttpSession session, HttpServletResponse response) {
        System.out.println("LoginCtrl.defaultKaptcha");
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");

        // 生成验证码字符串并保存到 session 中
        String capText = defaultKaptcha.createText();
        System.out.println("capText: " + capText);
        session.setAttribute("code", capText);

        // 向客户端写出
        BufferedImage bi = defaultKaptcha.createImage(capText);
        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
            ImageIO.write(bi, "jpg", out);
            out.flush();
        } catch (IOException e) {
            System.err.println("输出图形验证码失败");
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
